<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable :close-on-click-modal="false" :close-on-press-escape="false"
            width="50%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <!-- <el-menu
                :default-active="activeIndex"
                class="el-menu-demo"
                mode="horizontal"
                @select="handleSelect"
            >
                <el-menu-item index="1">集团组织</el-menu-item>
                <el-menu-item index="2">'友商组织'</el-menu-item>
            </el-menu> -->
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <template v-if="activeIndex === '2'">
                            <el-form-item label="友商名称" prop="name">
                                <el-input v-model="ruleForm.name" placeholder="友商名称" clearable />
                            </el-form-item>
                        </template>
                        <!-- <template v-if="activeIndex === '1'">
                            <el-form-item label="集团名称" prop="name">
                                <el-input v-model="ruleForm.name" placeholder="集团名称" clearable />
                            </el-form-item>
                        </template>
                        <template v-else>
                            <el-form-item label="友商名称" prop="name">
                                <el-input v-model="ruleForm.name" placeholder="友商名称" clearable />
                            </el-form-item>
                        </template> -->
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="唯一编码" prop="code">
                            <el-input v-model="ruleForm.code" placeholder="唯一编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="负责人" >
                            <el-input v-model="ruleForm.contacts" placeholder="负责人" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="联系电话" >
                            <el-input @blur="phoneBlur" v-model="ruleForm.tel" pattern="[0-9]" oninput="if(value.length>11)value=value.slice(0,11)" type="text" placeholder="联系电话" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="上传图片">
                            <div class="upload-d">
                                <el-upload
                                    ref="uploadFileOne"
                                    action="#"
                                    accept=".jpg,.png,.jpeg"
                                    :multiple="false"
                                    :show-file-list="false"
                                    :auto-upload='false'
                                    class="upload-style"
                                    :on-change="empImageChange"
                                    style="width:100%"
                                >
                                    <el-input v-if="!isViewOne" readOnly slot="" placeholder="上传图片" />
                                    <el-input v-if="isViewOne && !showImg" v-model="empImageVal" readOnly slot="" />
                                </el-upload>
                                <template v-if="isViewOne">
                                    <div v-if="showImg" style="color:#67C23A;" class="path_look">
                                        <span style="color:#0052D9;cursor:pointer;">查看</span>
                                    </div>
                                    <div class="icon-d upload-b">
                                        <el-tooltip effect="dark" content="移除" placement="top">
                                            <el-icon @click="cancelDepClickOne" style="background: unset !important;cursor:pointer;">
                                                <Delete />
                                            </el-icon>
                                        </el-tooltip>
                                    </div>
                                </template>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="备注">
                            <el-input v-model="ruleForm.remark" type="textarea" placeholder="备注" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)" type="primary">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus';
import { sysOrgAdd , AttendanceRecordGenerateId , sysFileInfoUploadfile } from '/@/api/centerControl/oms';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
import { emit } from 'process';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    // file: String, // 文件
    type: Number, // 机构类型（1集团，2友商）
    contacts: String, // 负责人
    tel: String, // 电话
    remark: String, // 备注
    status: Number, // 状态
    name: String, // 集团/友商名称
    code: String, // 编码
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        // const { proxy } = useCurrentInstance();
        // const $t = proxy.$t;
        
        const titleCon = ref()
        const ruleFormRef = ref()
        const activeIndex = ref('2')
        let snowflakeId:any = ''
        const uploadFileOne:Ref = ref()
        const pathData = ref(import.meta.env.VITE_API_URL + '/') // 获取地址
        const isViewOne = ref(false)
        const showImg = ref(false)
        const empImageVal = ref('')

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })
        
        /*** empImageChange 上传员工照片改变事件 */
        const empImageChange = (item:any,fileList:any) => {
            if (fileList.length > 1) {
                fileList.splice(0, 1); // 当上传文件大于1的时候替换，移除之前的文件（0是要删除数组的下标，1是要删除的数量）
            }
            isViewOne.value = true
            empImageVal.value = item.name
            uploadFileFun(item.raw)
        }
        /*** uploadFileFun 文件上传函数 */
        const uploadFileFun = async(file:any) => {
            let param:any = {}
            param.file = [file]
            param.sourceType = 'OMS'
            param.sourceId = snowflakeId
            console.log(param);
            let res:any = await sysFileInfoUploadfile(param)
            if(res.success) {
                emits('updateDateTree')
            }
        }

        /*** cancelDepClickOne 人员图像上传移除文件 */
        const cancelDepClickOne = () => {
            ElMessage({
                message: '删除成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                    uploadFileOne.value.clearFiles()
                    empImageVal.value = ''
                    isViewOne.value = false
                    showImg.value = false
                    // state.ruleForm.file = ''
                }
            })
        }

        /*** phoneBlur 手机号码失去焦点事件 */
        const phoneBlur = () => {
            let val = state.ruleForm.tel.replace(/\s*/g,"")
            if(val.length !== 11){
                state.ruleForm.tel = ''
            }else{
                if(isNaN(parseFloat(val))){
                    state.ruleForm.tel = ''
                }else{
                    if(parseFloat(val).toString().length !== 11){
                        state.ruleForm.tel = ''
                    }
                }
            }
        }

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 集团/友商名称
            name: [
				{ required: true, message: '请输入组织名称', trigger: 'blur' },
			],
            // 负责人
            contacts: [
                { required: true, message: '请输入负责人', trigger: 'blur' },
            ],
            // 电话
            tel: [
                { required: true, message:  '请输入联系电话', trigger: 'blur' },
            ],
            // 编码
            code: [
                { required: true, message: '请输入编码', trigger: 'blur' },
            ]
        })

        /*** handleSelect 菜单按钮选择事件 */
        const handleSelect = (val:any) => {
            activeIndex.value = val
            state.ruleForm.type = Number(val)
        }

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if(valid){
                    state.repeatDis = true
                    let getData = toRaw(state.ruleForm)
                    let param:any = {}
                    param.id = snowflakeId // 雪花id
                    let valObj = { ...getData , ...param }
                    let res:any = await sysOrgAdd(valObj)
                    if(res.success){
                        ctx.emit('updateData')
                        ctx.emit('controlUseClick')
                        state.repeatDis = false
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
            uploadFileOne.value.clearFiles()
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                // 状态数据重置
                state.repeatDis = false
                isViewOne.value = false
                showImg.value = false
                empImageVal.value = ''
                // 状态数据重置

                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                }else{
                    titleCon.value = '新增'
                    state.ruleForm.type = 2 // 机构类型（1集团，2友商）
                    state.ruleForm.contacts = '' // 负责人
                    state.ruleForm.tel = '' // 电话
                    state.ruleForm.name = '' // 集团/友商名称
                    state.ruleForm.status = 0 // 状态
                    state.ruleForm.code = '' // 编码
                    state.ruleForm.remark = '' // 备注
                    getNeedId()
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** getNeedId 获取雪花id */
        const getNeedId = async () => {
            let res:any = await AttendanceRecordGenerateId()
            if(res.success) snowflakeId = res.data
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            handleSelect,
            activeIndex,
            phoneBlur,
            uploadFileOne,
            pathData,
            isViewOne,
            showImg,
            empImageVal,
            empImageChange,
            cancelDepClickOne,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.is-active){
        background: rgba($color: #000000, $alpha: 0)!important;
    }
    :deep(.el-link){
        font-size: 12px;
    }
    .el-menu-demo{
        margin-bottom: 20px;
    }
    .upload-d{
        position: relative;
        width: 100%;
        :deep(.el-upload){
            width: 100%;
        }
        .path_look{
            display: block;
            width: 100%;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            position: absolute;
            left: 0;
            top: 0;
            span{
                display: block;
                margin-left: 15px;  
                color: #606266;
            }
        }
        .upload-in{
            position: absolute;
            left: 0;
            top: 0;
        }
        .select-btn-s{
            position: absolute;
            top: 2px;
            right: 1px;
            z-index: 3;
            margin: 0!important;
            border: none!important;
            background: rgba(255,255,255,1)!important;
            color: #0052D9!important;
            height: 28px;
        }
        .select-btn-s:active{
            color: #0052D9!important;
        }
        .select-btn-s:hover{
            color: #0052D9!important;
        }
        .upload-b{
            display: flex;
            align-items: center;
            position: absolute;
            top: 10px;
            right: 10px;
            line-height: initial;
            background: unset !important;
            :deep(a){
                background: unset !important;
                margin-right: 10px;
            }
            :deep(span){
                background: unset !important;
            }
        }
    }
</style>